package com.hilinos.ftp.api;

import com.hilinos.common.common.ReturnCode;
import com.hilinos.common.util.AssertUtils;
import com.hilinos.common.util.ServletUtils;
import com.hilinos.ftp.config.ServerConfig;
import com.hilinos.ftp.pojo.UserPojo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;

@Component
public class BaseApi {

    private static ServerConfig serverConfig;

    @Autowired
    public void setServerConfig(ServerConfig serverConfig) {
        BaseApi.serverConfig = serverConfig;
    }

    public static UserPojo getUser() {
        UserPojo userPojo = (UserPojo) ServletUtils.getRequest().getAttribute("userinfo");
        AssertUtils.isNotEmpty(userPojo, ReturnCode.AUTH_ERROR);
        return userPojo;
    }

    public static String getUserId() {
        return getUser().getUserid();
    }

    public static String getUserRelativePath(String path) {
        if (path == null) {
            path = "";
        }
        return ("admin".equals(getUserId()) ? "" : getUserId()) + File.separator + path;
    }

    /**
     * 获取用户根目录
     *
     * @return
     */
    public static File getUserRootDir() {
        return getUserFileOrDir(null);
    }

    /**
     * 获取用户文件/文件夹绝对路径
     *
     * @param path
     * @return
     */
    public static File getUserFileOrDir(String path) {
        if (path == null) {
            path = "";
        }
        File file = new File(serverConfig.getRootDir() + File.separator + getUserRelativePath(path));
        AssertUtils.isRex(file.exists(), ReturnCode.DATA_NOT_EXIST.respMsg("文件不存在"));
        return file;
    }

}
